import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { jumpToLogin, loadingInstance } from '@/utils/public';
import { getToken } from '@/utils/auth';
import { init } from '@/api/main';
// import menuData from '../public/menu.json'

NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  NProgress.start();

  const hasToken = getToken() && getToken() !== 'undefined';
  if (hasToken) {
    if (store.getters.permission_routes.length) {
      next();
    } else {
      initMenu(next, to, from);
    }
  } else {
    if (to.path === '/login') {
      next();
    } else {
      jumpToLogin();
      NProgress.done();
    }
  }
});

router.afterEach((to, from) => {
  // finish progress bar
  NProgress.done();
});

async function initMenu(next, to, from) {
  const loading = loadingInstance();
  // var menuList = []
  // for (var i in menuData.data) {
  //   var obj = {
  //     'alwaysShow': true,
  //     'children': [],
  //     'componentss': 'Layout',
  //     'hidden': 0,
  //     'icon': null,
  //     'menuFilePath': menuData.data[i].menuFilePath,
  //     'meta': {
  //       'actions': [],
  //       'icon': 'lock',
  //       'isHiddenTag': 0,
  //       'isTransition': 1,
  //       'target': 'iframe',
  //       'title': menuData.data[i].title
  //     },
  //     'name': 'menu_' + i,
  //     'path': menuData.data[i].menuFilePath,
  //     'redirect': ''
  //   }
  //   menuList.push(obj)
  // }
  // const accessRoutes = await store.dispatch('permission/generateRoutes', menuList)
  // router.addRoutes(accessRoutes)
  // next({ ...to })
  // loading.close()
  var params = {
    clientId: 'cdtye-itps-cms-client'
  };
  if (window.frames.length !== parent.frames.length) { // 判断是否在iframe中打开
    params.filterFlag = 'No';
  }
  init(params)
    .then(async(response) => {
      const accessRoutes = await store.dispatch('permission/generateRoutes', response.data);
      router.addRoutes(accessRoutes);
      next({ ...to });
      loading.close();
    }).catch(_ => {
      NProgress.done();
      loading.close();
    });
}
